class PeerPrice < ActiveRecord::Base
  
  validates :name,
    :uniqueness  => {
      :scope =>  :released_on
    }
  validates :model_no,
    :uniqueness  => {
      :scope =>  :released_on
    }
  validates :type_name,
    :name,
    :model_no,
    :released_on,
    :stock_situation,
    :status,
    :enterprise_id,
    :presence => true
  validates :peer_price,
    :trade_price,
    :retail_price,
    :numericality => {
      :greater_than => 0
    }
  
  belongs_to :cpu
  belongs_to :memory
  belongs_to :hard_disk
  belongs_to :enterprise
  
  scope :cpu, where( :type_name => 'cpu')
  scope :memory, where( :type_name => 'memory')
  scope :hard_disk, where( :type_name => 'hard_disk')
  scope :released, where(:status => 'released')
  scope :paused, where(:status => 'paused')
  
  scope :full, where(:stock_situation => 'full')
  scope :shortage, where(:stock_situation => 'shortage')
  scope :current_enterprise, lambda { where(:enterprise_id => Enterprise.id) }
  scope :default, where('id is not null')
  

  before_validation do |peer_price|
    peer_price.enterprise ||= Enterprise.current
  end
  
  def peer_price_link_index_type
    case
    when pre_one.nil?
      'keep'
    when peer_price > pre_one.peer_price
      'up'
    when peer_price < pre_one.peer_price
      'down'
    else
      'keep'
    end      
  end
  
  def peer_price_link_index_price
    pre_one.present? ? (peer_price - pre_one.peer_price) : 0
  end
  
  def trade_price_link_index_type
    case
    when pre_one.nil?
      'keep'
    when trade_price > pre_one.trade_price
      'up'
    when trade_price < pre_one.trade_price
      'down'
    else
      'keep'
    end      
  end
  
  def trade_price_link_index_price
    pre_one.present? ? (trade_price - pre_one.trade_price) : 0
  end
  
  def retail_price_link_index_type
    case
    when pre_one.nil?
      'keep'
    when retail_price > pre_one.retail_price
      'up'
    when retail_price < pre_one.retail_price
      'down'
    else
      'keep'
    end      
  end
  
  def retail_price_link_index_price
    pre_one.present? ? (retail_price - pre_one.retail_price) : 0
  end
  
  def pre_one
    PeerPrice.where(
      "name = ? and released_on < ?",
      name,
      released_on
    ).order('released_on desc').first
  end
end
